package com.gopay.checkorder.service.impl.expay;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import com.gopay.common.cipher.utils.LoggerMaskUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CmbcConstants;
import com.gopay.common.constants.bank.IpayConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.ipay.expay.Head;
import com.gopay.common.domain.bank.ipay.expay.IpayExPayBaseMessage;
import com.gopay.common.domain.bank.ipay.expay.Query;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 民生i支付快捷订单查询
 * @CheckOrderCmbcIpayExPayImpl.java
 * @author jiangxiangjiao
 */
public class CheckOrderIpayExPayImpl implements BankOrderService {
	private final static Logger logger = LoggerFactory.getLogger("CMBC");
	@Resource(name = "bankExPayClient")
	private ExPayInteractRemoteService bankExPayClient;
	
	@Resource(name = "bankOrderManager")
    protected BankOrderManager bankOrderManager;

	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String arg1) {
		logger.error("--------------bankExPayClient: "+ bankExPayClient);
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());

		IpayExPayBaseMessage message = new IpayExPayBaseMessage();
		message.setOrderId(bankOrder.getOrderId()); // 国付宝系统订单号
		message.setBankOrderId(bankOrder.getOutOrderId());
		message.setBank(bankOrder.getBankCode());
		message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
		message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(), "yyyyMMddHHmmss"));

		Result result = new Result();
		try {
			if(BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())){
				logger.error("===bankOrder:" + LoggerMaskUtils.maskString(ToStringBuilder.reflectionToString(bankOrder)) );
				message.setTkOriBankOrderId(bankOrder.getOriOutOrderId());
			}
			result = bankExPayClient.queryOrder(message);
			if (result == null || !result.isSuccess()) {
				logger.error("bankExPayClient fail.");
				if (result == null || ProcCodeConstants.PROC_CODE_100E6058.equals(result.getResultCode())) {
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}
			if(StringUtils.isNotBlank(result.getBankRetCode())){
				//add by liuyu, 20170803, 快捷API失败通知
				bankOrder.setBankRespCode(result.getBankRetCode());
			}

			IpayExPayBaseMessage res = (IpayExPayBaseMessage) result.getDefaultModel();
			if (res == null || !CmbcConstants.RESP_TYPE_SUCCESS.equals(res.getHead().getRespType())) {
				// 查询结果为空
				logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
						+ ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
			}
			//验签成功
			if(res.isVerifyFlag()){
				Head head = res.getHead();
				Query queryRes = (Query) res.getBody();
				//报文头成功
				if (IpayConstants.BANK_IPAY_DEAL_SUCCESS.equals(head.getRespType())
						&& IpayConstants.EX_RESP_CODE_SUCCESS.equals(head.getRespCode())) {
					// 交易成功
					if(IpayConstants.BANK_IPAY_DEAL_SUCCESS.equals(queryRes.getOriRespType())
							&& IpayConstants.EX_RESP_CODE_SUCCESS.equals(queryRes.getOriRespCode())){
						checkOrderResult.setSuccess(true);
						InAccInfo accInfo = new InAccInfo();
						accInfo.setOrderId(bankOrder.getOrderId());
						accInfo.setAmount(new BigDecimal(queryRes.getOriAmount()));
						accInfo.setRetCode("00");
						accInfo.setCardType(BankCardType.Unknown.toString());
						checkOrderResult.setAccInfo(accInfo);
						
						bankOrderManager.updateBankOrderId(bankOrder.getOutOrderId(), queryRes.getOriPayMsgId());
						logger.error("民生i支付快捷订单：" + bankOrder.getOrderId() + "的交易成功" + "返回码：" + head.getRespCode() + "返回信息："
								+ head.getRespMsg());
					// 原交易不存在
					}else if(IpayConstants.BANK_IPAY_DEAL_DEALING.equals(queryRes.getOriRespType())
							&& IpayConstants.TRAN_IPAY_NOT_EXIST.equals(queryRes.getOriRespCode())){
						
						checkOrderResult.setErrMsg("系统返回对账结果为空,订单已受理，请耐心等待");
						logger.error("民生i支付快捷订单：" + bankOrder.getOrderId() + "的交易成功" + "返回码：" + head.getRespCode() + "返回信息："
								+ head.getRespMsg());
					//交易失败						
					}else if(IpayConstants.BANK_IPAY_DEAL_ERROR.equals(queryRes.getOriRespType())){
						//退款金额超过可退余额,不做处理
//						if(IpayConstants.TRAN_IPAY_NOT_ENOUGH.equals(queryRes.getOriRespCode())){
//							checkOrderResult.setErrMsg("银行返回交易处理中");
//							checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);//查询订单不存在
//							logger.error("民生i支付快捷订单：" + bankOrder.getOrderId() + "的交易退款金额超过可退余额，当成订单不存在处理，" + "返回码：" + queryRes.getOriRespCode()
//									+ "返回信息：" + queryRes.getOriRespMsg());
//						}else{
							checkOrderResult.setErrMsg("银行返回交易失败");
							checkOrderResult.setBankFailure(true);
							
							InAccInfo accInfo = new InAccInfo();
							accInfo.setOrderId(bankOrder.getOrderId());
							accInfo.setAmount(new BigDecimal(queryRes.getOriAmount()));
							accInfo.setRetCode("01");
							accInfo.setCardType(BankCardType.Unknown.toString());
							checkOrderResult.setAccInfo(accInfo);
							logger.error("民生i支付快捷订单：" + bankOrder.getOrderId() + "的交易失败" + "返回码：" + queryRes.getOriRespCode() + "返回信息："
									+ queryRes.getOriRespMsg());
//						}
					//其他状态
					} else {
						checkOrderResult.setErrMsg("银行返回交易处理中");
						logger.error("民生i支付快捷订单：" + bankOrder.getOrderId() + "的交易未知，系统暂不处理" + "返回码：" + queryRes.getOriRespCode()
								+ "返回信息：" + queryRes.getOriRespMsg());
					}
				//报文头失败
				} else {
					checkOrderResult.setErrMsg("银行返回交易处理中");
					logger.error("民生i支付快捷订单：" + bankOrder.getOrderId() + "的交易未知，系统暂不处理" + "返回码：" + queryRes.getOriRespCode()
							+ "返回信息：" + queryRes.getOriRespMsg());
				}
			//验签失败
			}else{
				checkOrderResult.setErrMsg("银行返回验签失败");
                logger.error("民生i支付快捷支付订单：" + bankOrder.getOrderId() + "验签失败" + "返回码：" + res.isVerifyFlag());
			}
			
			return checkOrderResult;
		} catch (Exception e) {
			logger.error(bankOrder.getOrderId() + ": bankExPayClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("民生i支付快捷对账异常");
			return checkOrderResult;
		}
	}
	
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
